<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');

$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST["year"];
$staffId = $_POST['staffId'];

$startHour = $_POST['startHour_'.$staffId];
$startMinute = $_POST['startMinute_'.$staffId];
$endHour = $_POST['endHour_'.$staffId];
$endMinute = $_POST['endMinute_'.$staffId];

$tmp_date=date("Ymd");
$tmp_year=substr($tmp_date,0,4) * 1;
$tmp_mon =substr($tmp_date,4,2) * 1;
$tmp_day = substr($tmp_date, 6, 2) * 1;

if( $year < $tmp_year || ($year == $tmp_year&&$month < $tmp_mon) ){
	Output::Json("month is invalide", 1);
}

$tempStaff = Staff::getById($staffId);

$now = mktime(0, 0, 0, $tmp_mon, $tmp_day, $tmp_year);
$data=null;
$result = 0;
foreach($day as $k => $v){
	$indexTime = mktime(0, 0, 0, $month, $v, $year);
	if( $indexTime < $now ){
		Logs::setLog(" workSchedule is null ==");
		//$result = 1;
		continue;
	}
	if( $startHour[$k] > $endHour[$k] || ($startHour[$k] == $endHour[$k] && $startMinute[$k] >= $endMinute[$k]) ){
		Logs::setLog(" workSchedule is null ==1||".$startHour[$k]."||".$endHour[$k]."||".$startMinute[$k]."||".$endMinute[$k]);
		continue;
	}
	
	
	if( $startHour[$k] == 0 ){
		$endTime = mktime(23, 59, 59, $month, $v, $year);
		$temp = Preengage::HasOrdered($indexTime, $endTime, $staffId);
		if( $temp != null ){
			$data = $data."欠勤追加失敗しました(予約があります｜｜$year, $month, $v)。  ";
			$result = 1;
			continue;
		}
	
		$tempW = WorkSchedule::GetByYMD($staffId, $year, $month, $v);
		WorkSchedule::DeleteById($tempW['id']);
	}else if( $startHour[$k] != 0 && $startHour[$k] != null){
		WorkSchedule::Create($staffId, $year, $month, $v, $startHour[$k], $startMinute[$k], $endHour[$k], $endMinute[$k]);
		$tempUser = Users::GetUser($login_user_id);
		
		$log = $tempUser['family_name']." ".$tempUser['personal_name']."は".$tempStaff['family_name']." ".$tempStaff['personal_name']."の$year-".sprintf("%02d",$month)."-".sprintf("%02d",$v)."の勤務時間を登録しました。";
		AccessHistory::Create($login_user_id, $log);
	}
}
if( $result == 0 ){
	Output::Json(0);
}else{
	Output::Json($data, 1);
}

